// src/composables/useApproval.ts
import type { Ref } from 'vue'
// const layer = uni.$utils.layer;
// import layer from '@/common/comFun/layer';

// 定义页面需要传进来的数据和方法
export interface ApprovalOptions {
	approvalConfig : any
	globalData : any
	formData : Record<string, any>
	keyName : Ref<string>   // 改成 Ref<string>
	keyValue : Ref<any>     // 改成 Ref<any>
	enabledSubmitBtn : Ref<boolean> // 改成 Ref<boolean>
	detailName ?: string
	ApprovalID ?: any
	ApprovalSort ?: any
	physicalTableName ?: any
	UserInfo : any

	// pinia
	inventoryStore : any;
	mainStore : any;

	// 页面方法
	refreshPage : () => void
	openNextPage ?: () => void

	// 外部依赖
	run : any
	post : any,
	requestByUrl : any
	$popup ?: any
	$utils ?: any
	$store ?: any
}

export function useApproval(options : ApprovalOptions) {
	/** 发起审批 */
	function startApprove() {
		console.log(options.approvalConfig);
		//判定是否启用审批流
		if (options.approvalConfig.isEnableApproval) {
			// 二开配置项数据
			let globalData = options.globalData.ds[0];
			// console.log(globalData);

			//判断审批流的类型
			let approvalSql = "select * from SYS_BillAPFlow a where isnull(Type,'')!='999' and APPFormID=" + globalData.Id + "  ";

			options.requestByUrl({
				config: { baseURL: "/SQLData/QuerySql" },
				url: '',
				method: 'POST',
				data: {
					sql: approvalSql
				},
				success: (ret : any) => {
					console.log(ret);
					if (ret.status == 200) {
						const apType1Items = ret.data.ds.filter((item : any) => item.APType == 1);
						let filterData = apType1Items.length > 0 ? apType1Items : ret.data.ds.filter((item : any) => item
							.APType == 2);
						if (filterData.length) {
							configApprove(filterData);
						} else {
							uni.$utils.layer.msg('该单据暂未配置审批流方式');
							options.enabledSubmitBtn.value = true;
						};
					}
				}

			})


		}
	}

	/** 根据APType启用不同的审批流 */
	function configApprove(approveInfo : any[]) {
		const globalData = options.globalData.ds[0]
		// console.log(globalData);

		if (approveInfo[0].APType == 1) {
			// 固定审批流
			uni.$utils.$popup.show({
				option: approveInfo,
				globalData,
				keyName: options.keyName.value,
				keyValue: options.keyValue.value,
				confirm: () => {
					const work = options.approvalConfig.workConfig[0]
					let script = work.script.replace(/vm\./g, '');
					script = script.replace(/(?<![A-Za-z])(\[\s*['"])/g, 'options.formData$1');
					script = script.replace(/(?<![A-Za-z0-9_])post\(/g, 'options.post(');
					script = script.replace(/(?<![A-Za-z0-9_])refreshPage\(/g, 'options.refreshPage(');

					// eval(script)
					console.log(script);
					options.run(`
					${script}
					`, {
						// 注入UniApp环境的API（如uni对象）
						uni: uni,
						options: options,
						layer: uni.$utils.layer,
						work
					})

					options.refreshPage()
				},
				cancel: () => {
					options.enabledSubmitBtn.value = true
				},
			});
		} else {
			// 非固定审批流
			console.log(options.inventoryStore.st_comPageConfig.approveObj);
			let approveObj = uni.$utils.deepClone(
				options.inventoryStore.st_comPageConfig.approveObj
			)
			approveObj['workFlowDef']['name'] = approveInfo[0].BillName
			options.mainStore.BaseScreenParm = {
				option: approveInfo,
				globalData,
				keyName: options.keyName.value,
				keyValue: options.keyValue.value,
				approveObj,
			};

			uni.navigateTo({
				url: '/commonPage/m-node-warp/componentsPage/m-global-popup/m-node-warp-page',
				events: {
					doneConfirm: (data : any) => {
						const work = options.approvalConfig.workConfig[data];

						let script = work.script.replace(/vm\./g, '');
						script = script.replace(/(?<![A-Za-z])(\[\s*['"])/g, 'options.formData$1');
						script = script.replace(/(?<![A-Za-z0-9_])post\(/g, 'options.post(');
						script = script.replace(/(?<![A-Za-z0-9_])refreshPage\(/g, 'options.refreshPage(');
						console.log(script);
						console.log(options.formData['SiOrderID']);

						// eval(script)
						options.run(`
						${script}
						`, {
							// 注入UniApp环境的API（如uni对象）
							uni: uni,
							options: options,
							layer: uni.$utils.layer,
							work
						})
					},
					cancel: () => {
						options.enabledSubmitBtn.value = true
					},
				},
			})
		}
	}

	/** 审批单据 */
	function formApprove() {
		const globalData = options.globalData.ds[0]
		// console.log(globalData);
		uni.$utils.$popup.showFormApprove({
			globalData: globalData,
			keyName: options.keyName.value,
			keyValue: options.keyValue.value,
			ApprovalID: options.ApprovalID.value,
			ApprovalSort: options.ApprovalSort.value,
			Status: options.formData.Status,
			confirm: (data : any) => { // 确认按钮
				// 刷新页面
				options.refreshPage();
			},
			doneConfirm: (data : any) => { // 触发按钮的加载完事件脚本
				let workConfig = options.approvalConfig.workConfig

				let work = workConfig[data];

				let script = work.script.replace(/vm\./g, '');
				script = script.replace(/(?<![A-Za-z])(\[\s*['"])/g, 'options.formData$1');
				script = script.replace(/(?<![A-Za-z0-9_])post\(/g, 'options.post(');
				script = script.replace(/(?<![A-Za-z0-9_])refreshPage\(/g, 'options.refreshPage(');

				// eval(script);
				options.run(`
				${script}
				`, {
					// 注入UniApp环境的API（如uni对象）
					uni: uni,
					layer: uni.$utils.layer,
					options: options,
					work
				})
				// 刷新页面
				options.refreshPage();

				// 打开下一张单据
				options?.openNextPage && options.openNextPage();

			},
			cancel: (data) => {
				options.enabledSubmitBtn.value = true;

			}
		})
	}

	/** 取消审批 */
	function cancelApprove() {
		uni.$utils.layer.confirm("是否撤销审批", function (res : any) {
			console.log(res);
			const { action } = res;

			switch (action) {
				case 'cancel':
					options.enabledSubmitBtn.value = true;
					break;
				case 'confirm':
					const param = {
						tableName: options.physicalTableName.value,
						keyName: options.keyName.value,
						keyId: options.keyValue.value,
						userId: options.UserInfo.UserID,
					}
					console.log(param);
					options.requestByUrl({
						config: { baseURL: "/Approve/cancelApproval" },
						url: '',
						method: 'POST',
						data: param,
						success: (ret : any) => {
							console.log(ret);
							if (ret.status == 200) {
								switch (ret.data.ds[0].Status) {
									case 500:
										uni.$utils.layer.alert(ret.data.ds[0].msg);
										options.enabledSubmitBtn.value = true;
										break;
									case 200:
										uni.$utils.msg("撤销审批成功");
										options.refreshPage();
										break;
									default:
										options.enabledSubmitBtn.value = true;
										break;
								}

							}
						}

					})
					break;
				default:
					break;
			}
		});


	}

	/** 查阅审批流 */
	function viewListApprove() {
		const globalData = options.globalData.ds[0]
		// console.log(globalData);
		uni.$utils.$popup.showListApprove({
			tableName: options.physicalTableName.value,
			globalData: globalData,
			keyName: options.keyName.value,
			keyValue: options.keyValue.value,
			ApprovalID: options.ApprovalID.value,
			ApprovalSort: options.ApprovalSort.value,
			Status: options.formData.Status,
			confirm: (data) => { // 确认按钮 

			},
			cancel: (data) => {
				options.enabledSubmitBtn.value = true;

			}

		})
	}

	return {
		startApprove,
		configApprove,
		formApprove,
		cancelApprove,
		viewListApprove,
	}
}